<?php

	// define('IN_NWIDC',1);
	// define('APP_ID','shop');
	// define('BASE_PATH',str_replace('\\','/',dirname(__FILE__) . '/shop'));
	// if (!@include(dirname((__FILE__)).'/global.php')) exit('global.php isn\'t exists!');
	// if (!@include(BASE_PATH.'/control/control.php')) exit('control.php isn\'t exists!');
	// if (!@include(BASE_CORE_PATH.'/nwidc.php')) exit('nwidc.php isn\'t exists!');
	// define('APP_SITE_URL',SHOP_SITE_URL);
	// define('TPL_NAME',TPL_SHOP_NAME);
	// define('SHOP_RESOURCE_SITE_URL',SHOP_SITE_URL.DS.'resource');
	// define('SHOP_TEMPLATES_URL',SHOP_SITE_URL.'/templates/'.TPL_NAME);
	// define('BASE_TPL_PATH',BASE_PATH.'/templates/'.TPL_NAME);

	require_once(dirname(BASE_PATH) . '/custom/hangzhou/hangzhou_define.php');

	set_time_limit(0);

	$param = array(
		'ip' => '127.0.0.1',
		'v' => '1.0',
		// 'appKey' => 'SPWLA',
		'company_code' => 'SPWL',
		'sessionKey' => '2015SPWLAV1'
	);

	/**
	 * 一共4个接口
	 * 商品备案、订单备案、订单状态、订单发货
	 */

	$send_goods_url = 'http://60.191.39.196:8001/ecm/interface/rest/SPWLInterface/sendCommodity';
	$send_order_url = 'http://60.191.39.196:8001/ecm/interface/rest/SPWLInterface/pushSaleOrder';
	$porder_url = '';

	if(isset($_GET['interface'])){
		$interface = trim($_GET['interface']);

		//回传实际入库数量
		//这个接口不用了
		if($interface == 'sendRealStockInAmount'){
			$json = json_decode(base64_decode($_POST['JSON_OBJ']),true);
			//存储下原始数据
			@file_put_contents('sendRealStockInAmount_' . time() . '.txt',var_dump($json,true));

			try{
				foreach($json['porderList'] as $key => $val){
					//更新订单状态
					$time = strtotime($val['callInDate']);
					Model('hangzhou_order')->where(array('code' => $val['code']))->update(array(
						'status' => HANGZHOU.SUCCESS,
						'time' => $time
					));

					//更新商品状态
					$id = Model('hangzhou_order')->where(array('code' => $val['code']))->find();
					$id = $id['id'];
					foreach($val['Item'] as $g){
						Model('hangzhou_order_goods')->where(array('order_id' => $id , 'commodityBarcode' => $g['commodityBarcode']))->update(array(
							'RealInQty' => $g['RealInQty'],
							'damageNum' => $g['damageNum']

						));

						//按照commonid来更新goods表中和goods_common表中的状态以及数量
						$goods_commonid = Model('hangzhou_order_goods')->where(array('order_id' => $id,'commodityBarcode' => $g['commodityBarcode']))->find();
						$goods_commonid = $goods_commonid['goods_commonid'];

						//防止数据出错
						if(empty($goods_commonid)){
							continue;
						}

						Model()->table('goods')->where(array('goods_commonid' => $goods_commonid))->update(array(
							'goods_storage' => $g['RealInQty'],
							'goods_verify' => 1
						));
						Model()->table('goods_common')->where(array('goods_commonid' => $goods_commonid))->update(array(
							'goods_storage' => $g['RealInQty'],
							'goods_verify' => 1
						));

						//更新ra_hangzhou_goods表中的状态
						Model('hangzhou_goods')->where(array('goods_commonid' => $goods_commonid))->update(array(
							'status' => HANGZHOU.SUCCESS
						));

					}
				}

				$result = array(
					'Response' => array(
						'resultCode' => '1000',
						'resultMsg' => '接收成功'
					)
				);
				exit(json_encode($result));


			}
			catch(Exception $e){

				$result = array(
					'Response' => array(
						'resultCode' => '1005',
						'resultMsg' => '接收失败'
					)
				);
				exit(json_encode($result));
			}


			exit;
		}



		if($interface == 'sendShipOrder'){
			$json = json_decode(base64_decode($_POST['JSON_OBJ']),true);
			//存储下原始数据
			@file_put_contents('sendShipOrder_' . time() . '.txt',print_r($json,true));

			$result = array(
					'ROWSET' => array(
						'resultCode' => 1000,
						'resultMsg' => '接收成功'
					)
				);
			exit(json_encode($result));

			exit;

			$failed = array();

			foreach($json['SHIPPORDERS'] as $order){
				$order_sn = substr($order['orderCode'],8);

				//check this order's state and must be 20
				$order_info = Model('order')->where(array('order_sn' => $order_sn))->find();
				if($order_info['order_state'] != 20){
					$failed[] = $order['orderCode'];
				}
				Model('order')->where(array('order_sn' => $order_sn))->update(
					array(
						'shipping_code' => $order['expressNo'],
						'order_state' => 30,
						'hangzhou_details' => json_encode($order),
						'hangzhou_state' => HANGZHOU.SUCCESS
					)
				);

				if($order['companyNo'] == 'EMS'){
					$ship_id = 8;
				}
				elseif($order['companyNo'] == 'ZTO'){
					$ship_id = 44;
				}
				else{
					$ship_id = 28;
				}

				Model('order_common')->where(array('order_id' => $order_info['order_id']))->update(array(
					'shipping_time' => $order['shippingTime'],
					'shipping_express_id' => $ship_id
				));

				//更新订单商品中实际的数量
				foreach($order['details'] as $goods){
					$goods_commonid = Model('custom_hangzhou_goods')->where(array('commodityCode' => $goods['commodityCode']))->find();
					$goods_commonid = $goods_commonid['goods_commonid'];
					Model('order_goods')->where(array('order_id' => $order_info['order_id'],'goods_commonid' => $goods_commonid))->update(array(
						'real_count' => $goods['qty'],
						'hangzhou_details' => json_encode($goods)
					));
				}

			}

			if(count($failed)){
				$arr = array();
				foreach($failed as $f){
					$arr[] = array(
						'code' => $f,
						'errorMsg' => '订单状态已变更，发货失败'
					);
				}
				$result = array(
					'ROWSET' => array(
						'resultCode' => count($failed) == count($json['SHIPPORDERS']) ? 1005 : 1015,
						"resultMsg" => '部分失败',
						'ERROR' => $arr
					)
				);
				// $result = array()
			}
			else{
				$result = array(
					'ROWSET' => array(
						'resultCode' => 1000,
						'resultMsg' => '接收成功'
					)
				);

			}

			exit(json_encode($result));
		}


		if($interface == 'sendOrderStatus'){
			$json = json_decode(base64_decode($_POST['JSON_OBJ']),true);
			//存储下原始数据
			@file_put_contents('sendShipOrder_' . time() . '.txt',print_r($json,true));

			@file_put_contents('send_log.txt',print_r($GLOBALS,true));
			$result = array(
					'ROWSET' => array(
						'resultCode' => 1000,
						'resultMsg' => '接收成功'
					)
				);
			exit(json_encode($result));
		}


		exit;
	}


	/**
	 * 新上架商品备案
	 */
	if(false){
	echo '检索备案中的的商品' . PHP_EOL;
	echo '<br>';

	$sql = "select * from ra_goods_common where goods_verify = 10 and open_tax = 1 limit 500";
	$goods = Model()->query($sql);
	$json = array('Commoditys' => array());

	//商品编号
	$id = Model('hangzhou_goods')->order('id desc')->find();
	$id = $id['id'];
	if(empty($id)){
		$id = 0;
	}

	for($i = 0; $i < 500 && $i < count($goods); $i++){
		$item = $goods[$i];

		$store_info = Model('store')->find($item['store_id']);

		//已经关闭的店铺不能参与！
		if($store_info['store_state'] != 1){
			continue;
		}

		$id++;
		$str = $id;
		for($i = strlen($id); $i < 4; $i++){
			$str = '0' . $str;
		}

		$data = array(
			'goods_extend' => Model('custom_hangzhou_goods')->where(array('goods_commonid' => $item['goods_commonid']))->find(),
			'goods_common' => $item
		);


		$json['Commoditys'][] = array(
			"commodityCode" => $param['company_code'] . $str,
			"commodityName" => $data['goods_common']['goods_name'],
			'commoditySpec' => isset($data['goods_extend']['commoditySpec']) ? $data['goods_extend']['commoditySpec'] : '',
			'commodityArtNo' => isset($data['goods_extend']['commodityArtNo']) ? $data['goods_extend']['commodityArtNo'] : '',
			'commodityMadeTime' => isset($data['goods_extend']['commodityMadeTime']) ? $data['goods_extend']['commodityMadeTime'] : '',
			'durabilityPeriod' => isset($data['goods_extend']['durabilityPeriod']) ? $data['goods_extend']['durabilityPeriod'] : '',
			'brandId' => isset($data['goods_common']['brand_id']) ? $data['goods_common']['brand_id'] : '',
			'brandName' => isset($data['brand_name']['brand_name']) ? $data['goods_common']['brand_name'] : '',
			'price' => isset($data['goods_common']['goods_costprice']) ? $data['goods_common']['goods_costprice'] : '',
			'marketPrice' => isset($data['goods_common']['goods_marketprice']) ? $data['goods_common']['goods_marketprice'] : '',
			'serialcontrol ' => isset($data['goods_extend']['serialcontrol ']) ? $data['goods_extend']['serialcontrol '] : '',
			'typeId' => isset($data['goods_common']['gc_id']) ? $data['goods_common']['gc_id'] : '',
			'unit' => isset($data['goods_extend']['unit']) ? $data['goods_extend']['unit'] : '',
			'weight' => isset($data['goods_extend']['weight']) ? $data['goods_extend']['weight'] : '',
			'boxSpec' => isset($data['goods_extend']['boxSpec']) ? $data['goods_extend']['boxSpec'] : '',
			'remark' => isset($data['goods_extend']['remark']) ? $data['goods_extend']['remark'] : '',
			'madeAddr' => isset($data['goods_extend']['madeAddr']) ? $data['goods_extend']['madeAddr'] : '',
			'tradeCountryName' => isset($data['goods_extend']['tradeCountryName']) ? $data['goods_extend']['tradeCountryName'] : '',
			'tradeCountryCode ' => isset($data['goods_extend']['tradeCountryCode']) ? $data['goods_extend']['tradeCountryCode'] : '',
			'HScode' => isset($data['goods_extend']['HScode']) ? $data['goods_extend']['HScode'] : '',

			'goods_commonid' => $data['goods_common']['goods_commonid']
		);
	}

	//将这些数组按照commodityCode分类
	$readyArr = array();
	foreach($json['Commoditys'] as $key => $val){
		$readyArr[$val['commodityCode']] = $val;

		//去除goods_commonid
		unset($val['goods_commonid']);
		$json['Commoditys'][$key] = $val;
	}

	print_r($json);
	//商品备案测试
	if(count($json['Commoditys'])){
		send_post($send_goods_url,$json,function($result) use (&$readyArr){
			//处理失败的地方
			if($result['resultCode'] != 1000){
				foreach($result['ERROR'] as $key => $item){
					$readyArr[$item['code']]['status'] = 'failed';
				}
			}
			// print_r($resutl);

			//将对的部分插入数据库
			foreach($readyArr as $key => $val){
				Model('hangzhou_goods')->insert(
					array(
						'commodityCode' => $val['commodityCode'],
						'goods_commonid' => $val['goods_commonid'],
						'status' =>  empty($val['status']) ? HANGZHOU.WAITING : HANGZHOU.FAILED
					)
				);
			}


		});
	}

	echo 'SUCCESS' . PHP_EOL;
	echo '<br>';



	/**
	 * 商品采购入库
	 */
	
	echo '采购这些商品' . PHP_EOL;
	echo "<br>";

	$sql = "select * from ra_hangzhou_goods where status = '0x01'";
	$PorderList = Model()->query($sql);

	$json = array('PorderList' => array());

	//整理成店铺索引的数组
	$arr = array();
	foreach($PorderList as $key => $val){
		if(!isset($arr[$val['store_id']])){
			$arr[$val['store_id']] = array();
		}
		$arr[$val['store_id']][] = $val;
	}

	$count = 0;
	foreach($arr as $store_id => $g){
		$store_info = Model('store')->find($val['store_id']);
		//已经关闭的店铺不能参与！
		if($store_info['store_state'] != 1){
			continue;
		}
		$item = array(
			'code' => time() . ($count++),
			'companyCode' => $goods['store_id'],
			'supplierCode' => $goods['store_id'],
			'supplierName' => $store_info['store_name'],
			'callInWarehouse' => 'FLHZ01',
			'totalAmount' => '',
			'type' => '',
			'status' => '',
			'Item' => array() 
		);
		$total = 0;
		foreach($g as $val){
			$goods = Model()->table('goods_common')->where(array('goods_commonid' => $val['goods_commonid']))->find();
			$extend = Model('custom_hangzhou_goods')->where(array('goods_commonid' => $val['goods_commonid']))->find();
			$item['Item'][] = array( 
				'commodityName' => $goods['goods_name'],
				'commodityBarcode' => $goods['sharp'],
				'shouldInQty' => $goods['goods_num'],
				'commodityPrice' => $goods['goods_price'],

				'goods_commonid' => $goods['goods_commonid']
			);
			$total += $goods['goods_price'] * $goods['goods_num'];
		}
		$item['totalAmount'] = $total;
		$json['PorderList'][] = $item;
	}

	if(count($json['PorderList'])){
		$backup = $json['PorderList'];
		//去除没用的commonid
		foreach($json['PorderList'] as $key => &$val){
			foreach($val['Item'] as $k => &$v){
				unset($v['goods_commonid']);
			}
		}

		send_post($porder_url,$json,function($result) use ($backup){
			if($result['resultCode'] != 1000){
				return;
			}
			//将这些个订单入库
			foreach($backup['PorderList'] as $key => $val){

				$id = Model('hangzhou_order')->insert(array(
					'code' => $val['code'],
					'time' => '',
					'companyCode' => $val['companyCode'],
					'status' => '0x01',
					'totalAmount' => $val['totalAmount']
				));

				if($id){
					foreach($val['Item'] as $g){
						Model('hangzhou_order_goods')->insert(array(
							'order_id' => $id,
							'commodityName' => $g['commodityName'],
							'commodityBarcode' => $g['commodityBarcode'],
							'shouldInQty' => $g['shouldInQty'],
							'goods_commonid' => $g['goods_commonid']
						));
					}
				}
				
			}
		});
	}

	}


	/**
	 * 订单备案
	 */
	echo "订单备案";
	echo '<br>';

	$sql = "select * from ra_order where hangzhou_state is null and order_state = 20 limit 500";
	$orders = Model()->query($sql);
	if(!count($orders)){
		$orders = array();
	}
	$json = array('Orders' => array());
	foreach($orders as $key => $order){
		$common = Model('order_common')->where(array('order_id' => $order['order_id']))->find();
		print_R($common);
		$store_info = Model('store')->find($order['store_id']);
		if($store_info['store_state'] != 1){
			continue;
		}

		$receiver_info = unserialize($common['reciver_info']);

		$province = Model('area')->find($common['reciver_province_id']);
		$province = $province['area_name'];
		$city = Model('area')->find($common['reciver_city_id']);
		$city = $city['area_name'];

		$item = array(
			"orderCode" => $param['company_code'] . $order['order_sn'],
			"orderDate" => date('Y-m-d H:i:s',$order['payment_time']),
			"outCode" => $order['order_sn'],
			"expressName" => '',
			"expressNo" => '',
			"receiverName" => $common['reciver_name'],
			"buyernick" => '',
			"mobile" => $order['phone'],
			"warehouseCode" => 'FLHZ01',
			"shopid" => $order['store_id'],
			"shop" => $store_info['store_name'],
			"buyerMessage" => $common['order_message'],
			"remark" => '',
			"systemRemark" => '',
			"telPhone" => '',
			"province" => $province,
			"city" => $city,
			"district" => '',
			"receiverAddress" => $receiver_info['address'],
			"receiverZip" =>'',
			"isCashOnDelivery" => '',
			"payType" => '03',
			"payCompanyCode" => '',
			"payNumber" => '',
			"orderTotalAmount" => $order['order_amount'],
			"orderGoodsAmount" => $order['goods_amount'],
			"orderTaxAmount" => $order['order_tax'],
			"feeAmount" => $order['shipping_fee'],
			"tradeTime" => date('Y-m-d H:i:s',$order['payment_time']),
			"currCode" => '142',
			"totalAmount" => '120.00',
			"purchaserId" => $order['buyer_id'],
			"id" => $order['buyer_id'],
			"name" => $order['buyer_name'],
			"telNumber" => $order['phone'],
			"paperType" => '01',
			"paperNumber" => $order['idcard'],
			"address" => $receiver_info['address'],
			'holdCode' => '本人承诺所购买商品系个人合理自用，现委托商家代理申报、代缴税款等通关事宜，本人保证遵守《海关法》和国家相关法律法规，保证所提供的身份信息和收货信息真实完整，无侵犯他人权益的行为，以上委托关系系如实填写，本人愿意接受海关、检验检疫机构及其他监管部门的监管，并承担相应法律责任.',
			'OrderDtls' => array()
		);

		//添加订单商品
		$goods = Model('order_goods')->where(array('order_id' => $order['order_id']))->select();
		foreach($goods as $g){
			$gcid = Model('goods')->find($g['goods_id']);
			$gcid = $gcid['goods_commonid'];
			$extend = Model('custom_hangzhou_goods')->where(array('goods_commonid' => $gcid))->find();
			$common = Model()->table('goods_common')->where(array('goods_commonid' => $gcid))->find();
			$item['OrderDtls'][] = array(
				'commodityCode' => $extend['commodityCode'],
				'commodityName' => $g['goods_name'],
				'commodityBarcode' => $g['sharp'],
				'commoditySpec' => $extend['commoditySpec'],
				'isSet' => '',
				'qty' => $g['goods_num'],
				'weight' => $extend['weight'],
				'buyerMessage' => '',
				'remark' => '',
				'tradePrice' => $g['goods_proxy'],
				'tradeTotal' => $g['goods_proxy'] * $g['goods_num'],
				'declPrice' => $g['goods_proxy'],
				'declTotalPrice' => $g['goods_proxy'] * $g['goods_num'],
				'codeTs' => $extend['codeTs']
			);
		}

		$json['Orders'][] = $item;
	}

	print_r($json);


	if(count($json['Orders'])){
		send_post($send_order_url,$json,function($result) use($json){
			print_R($result);
			if($result['resultCode'] != 1000){
				return;
			}
			#let these orders be locked
			foreach($json['Orders'] as $key => $val){
				$order_sn = substr($val['orderCode'],4);
				echo $order_sn;
				Model()->table('order')->where(array('order_sn' => $order_sn))->update(array(
					'hangzhou_state' => HANGZHOU.WAITING
				));
			}
		});
	}



	exit;


	function send_post($url,$json,$callback = null){
		$param = array(
			'ip' => '127.0.0.1',
			'v' => '1.0',
			// 'appKey' => 'SPWLA',
			'company_code' => 'SPWL',
			'sessionKey' => '2015SPWLAV1'
		);
		
		$param['JSON_OBJ'] = base64_encode(json_encode($json));
		$param['datetime'] = date("YmdHis");
		$sign = $param['v'] . $param['ip'] . $param['sessionKey'] . $param['datetime'] . 'SPWLA';
		$param['sign'] = strtoupper(md5($sign));

		$result = file_get_contents_post($url,$param);
		echo $result;

		if($callback){
			$result = json_decode($result,true);
			call_user_func($callback,$result['ROWSET']);
		}
	}

	function file_get_contents_post($url, $post) {  
	    $options = array(  
	        'http' => array(  
	            'method' => 'POST',  
	            // 'content' => 'name=caiknife&email=caiknife@gmail.com',  
	            'content' => http_build_query($post),  
	        ),  
	    );  

	    $result = file_get_contents($url, false, stream_context_create($options));  
	  
	    return $result;  
	}  
	//$goods = Model()->table('goods')->where(array('goods_verify' => 10))->select();
	// file_put_contents('lot.txt', 123456),
?>